# ui/main_window.py
from PySide6.QtWidgets import QMainWindow, QFileDialog, QVBoxLayout, QPushButton, QTextEdit, QLabel, QWidget
from PySide6.QtCore import Signal
from workers.makeword_worker import MakeWordWorker

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("教案生成工具")
        self.setGeometry(100, 100, 600, 400)
        
        self.template_path = None
        self.csv_file_path = None
        self.output_dir = "output"
        
        self.init_ui()
    
    def init_ui(self):
        self.layout = QVBoxLayout()
        
        self.text_edit = QTextEdit(self)
        self.text_edit.setReadOnly(True)
        self.layout.addWidget(self.text_edit)
        
        self.placeholders_label = QLabel(self)
        self.placeholders_label.setWordWrap(True)  # 允许自动换行
        self.layout.addWidget(self.placeholders_label)
        
        self.select_template_button = QPushButton("选择Word模板文件", self)
        self.select_template_button.clicked.connect(self.select_template_file)
        self.layout.addWidget(self.select_template_button)
        
        self.select_csv_button = QPushButton("选择CSV文件", self)
        self.select_csv_button.clicked.connect(self.select_csv_file)
        self.layout.addWidget(self.select_csv_button)
        
        self.generate_button = QPushButton("生成教案", self)
        self.generate_button.clicked.connect(self.generate_lessons)
        self.layout.addWidget(self.generate_button)
        
        self.central_widget = QWidget()
        self.central_widget.setLayout(self.layout)
        self.setCentralWidget(self.central_widget)
    
    def select_template_file(self):
        self.template_path, _ = QFileDialog.getOpenFileName(self, "选择Word模板文件", "", "Word Files (*.docx)")
        if self.template_path:
            self.text_edit.append(f"已选择Word模板文件: {self.template_path}")
            self.worker = MakeWordWorker(self.template_path, self.csv_file_path, self.output_dir)
            self.worker.placeholders_signal.connect(self.update_placeholders)
            self.worker.check_placeholders()
    
    def select_csv_file(self):
        self.csv_file_path, _ = QFileDialog.getOpenFileName(self, "选择CSV文件", "", "CSV Files (*.csv)")
        if self.csv_file_path:
            self.text_edit.append(f"已选择CSV文件: {self.csv_file_path}")
    
    def generate_lessons(self):
        if not self.template_path or not self.csv_file_path:
            self.text_edit.append("请先选择Word模板文件和CSV文件。")
            return
        
        self.worker = MakeWordWorker(self.template_path, self.csv_file_path, self.output_dir)
        self.worker.log_signal.connect(self.update_status)
        self.worker.start()
    
    def update_status(self, message):
        self.text_edit.append(message)
    
    def update_placeholders(self, placeholders):
        self.placeholders_label.setText(f"在 Word 模板中找到的占位符: {placeholders}")